﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QuickLifeHall.Facade.SystemBase
{
    public class Menu
    {
        DAL.SystemBase.Menu repository = new DAL.SystemBase.Menu();

        #region 页面操作

        [AjaxPro.AjaxMethod]
        public List<Entity.EasyUI.TreeNode> GetAllMenus(string jsonString)
        {
            List<Entity.SystemBase.Menu> allMenus = repository.GetList(PetaPoco.Sql.Builder).ToList();
            List<Entity.EasyUI.TreeNode> result = new List<Entity.EasyUI.TreeNode>();

            if (allMenus != null && allMenus.Count > 0)
            {
                foreach (Entity.SystemBase.Menu item in allMenus)
                {
                    if (item.ParentID == 0)
                    {
                        var treeNode = this.ConvertToTreeNode(item);
                        result.Add(treeNode);

                        foreach (Entity.SystemBase.Menu subItem in allMenus)
                        {
                            if (subItem.ParentID == item.MenuID)
                            {
                                if (item.children == null)
                                {
                                    item.children = new List<Entity.SystemBase.Menu>();
                                    treeNode.children = new List<Entity.EasyUI.TreeNode>();
                                }
                                item.children.Add(subItem);
                                treeNode.children.Add(this.ConvertToTreeNode(subItem));
                            }
                        }
                    }
                }
            }

            return result;
        }

        [AjaxPro.AjaxMethod]
        public List<Entity.EasyUI.TreeNode> GetChildrenMenu(int parentId)
        {
            var menus = repository.GetChildrenMenu(parentId);
            List<Entity.EasyUI.TreeNode> result = new List<Entity.EasyUI.TreeNode>();
            foreach (Entity.SystemBase.Menu item in menus)
            {
                result.Add(this.ConvertToTreeNode(item));
            }

            return result;
        }


        #endregion

        #region 私有方法

        private Entity.EasyUI.TreeNode ConvertToTreeNode(Entity.SystemBase.Menu menuEntity)
        {
            var result = new Entity.EasyUI.TreeNode();
            result.id = menuEntity.MenuID.ToString();
            result.text = menuEntity.MenuName;

            if (menuEntity.ChildrenCount > 0)
                result.state = "closed";
            else
                result.state = "open";

            if (!string.IsNullOrEmpty(menuEntity.Icon))
                result.iconCls = menuEntity.Icon;
            else
                result.iconCls = "icon-save";

            result.attributes.Add("entity", menuEntity);

            return result;
        }

        #endregion
    }
}
